defmodule EliPhxPlayWeb.Components.DashboardRight.HeaderComponent do
  use EliPhxPlayWeb, :live_component
  alias EliPhxPlay.Context.Accounts
  alias EliPhxPlay.Context.UserRelationship
def mount(socket) do
  {:ok, assign(socket,
    show_add_friend_modal: false,
    search_term_addf: "",
    search_results: [],
    selected_user: nil,
    show_notification: false,
    notification_type: nil,
    notification_message: ""
  )}
end


  def render(assigns) do
    ~H"""
    <div class="h-20 px-6 pt-5 border-b border-gray-200 flex-shrink-0 bg-white">
      <%= case @page_type do %>
        <% :recent_chats -> %>
          <%= render_recent_chats_header(assigns) %>
        <% :contacts -> %>
          <%= render_contacts_header(assigns) %>
        <% :settings -> %>
          <%= render_settings_header(assigns) %>
        <% _ -> %>
          <%= render_default_header(assigns) %>
      <% end %>
    </div>
    """
  end

  # 最近聊天页面标题
  defp render_recent_chats_header(assigns) do
    ~H"""
    <div class="flex items-center justify-between">
      <div class="flex items-center gap-3">
        <h1 class="text-2xl font-bold text-gray-900">最近聊天</h1>
        <%= if @data && length(@data) > 0 do %>
          <span class="bg-blue-100 text-blue-800 text-xs font-medium px-2.5 py-1 rounded-full">
            <%= length(@data) %> 个对话
          </span>
        <% end %>
      </div>

      <!-- 新建聊天按钮 -->
      <div class="flex items-center gap-3">
        <button
          phx-target={@myself}
          phx-click="new_chat"
          class="inline-flex items-center gap-2 bg-green-600 hover:bg-green-700 focus:ring-4 focus:ring-green-200 text-white px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 shadow-sm hover:shadow"
        >
          <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
          </svg>
          新建聊天
        </button>
      </div>
    </div>
    """
  end

  # 联系人页面标题
  defp render_contacts_header(assigns) do
    ~H"""
    <div class="flex items-center justify-between gap-6">
      <!-- 标题区域 -->
      <div class="flex items-center gap-3">
        <h1 class="text-2xl font-bold text-gray-900">联系人</h1>
        <span class="bg-gray-100 text-gray-600 text-xs font-medium px-2.5 py-1 rounded-full">
          <%= if @data, do: length(@data), else: 0 %>
        </span>
      </div>

      <!-- 搜索框区域 -->
      <div class="relative flex-1 max-w-md min-w-0">
        <div class="absolute inset-y-0 left-0 pl-2 sm:pl-3 flex items-center pointer-events-none">
          <svg class="w-4 h-4 sm:w-5 sm:h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
          </svg>
        </div>
        <input
          type="text"
          placeholder="搜索联系人..."
          phx-target={@myself}
          phx-keyup="search"
          phx-debounce="300"
          class="block w-full pl-8 sm:pl-10 pr-3 sm:pr-4 py-2.5 sm:py-3 text-sm sm:text-base border border-gray-300 rounded-lg bg-gray-50 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 focus:bg-white transition-all duration-200 placeholder-gray-400"
        />
      </div>

      <!-- 操作按钮区域 -->
      <div class="flex items-center gap-3">
        <button
          phx-target={@myself}
          phx-click="add_friend"
          class="inline-flex items-center gap-2 bg-blue-600 hover:bg-blue-700 focus:ring-4 focus:ring-blue-200 text-white px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 shadow-sm hover:shadow"
        >
          <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
          </svg>
          添加好友
        </button>
      </div>

      <!-- Modal -->
      <%= if @show_add_friend_modal do %>
        <div class="fixed inset-0 z-50 overflow-y-auto">
          <!-- 背景遮罩 -->
          <div
            class="fixed inset-0 bg-black bg-opacity-50 transition-opacity"
            phx-click="close_modal"
            phx-target={@myself}
          ></div>

          <!-- Modal 内容 -->
          <div class="flex min-h-full items-center justify-center p-4">
            <div class="relative bg-white rounded-lg shadow-xl max-w-md w-full">
              <!-- Modal 头部 -->
              <div class="flex items-center justify-between p-6 border-b">
                <h3 class="text-lg font-semibold text-gray-900">添加好友</h3>
                <button
                  phx-click="close_modal"
                  phx-target={@myself}
                  class="text-gray-400 hover:text-gray-600"
                >
                  <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                  </svg>
                </button>
              </div>

              <!-- Modal 内容 -->
              <div class="p-6">
                  <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">
                      用户昵称或账号
                    </label>
                    <input
                      type="text"
                      name="friend_identifier"
                      phx-keyup="search_users"
                      phx-debounce="300"
                      phx-target={@myself}
                      value={@search_term_addf || ""}
                      class="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      placeholder="用户昵称或账号"
                      required
                    />

                    <!-- 搜索结果显示 -->
                    <%= if @search_results && length(@search_results) > 0 do %>
                      <div class="mt-2 bg-white border border-gray-300 rounded-md shadow-lg max-h-48 overflow-y-auto">
                        <%= for user <- @search_results do %>
                          <div class="px-4 py-2 hover:bg-gray-50 border-b last:border-b-0 flex items-center justify-between">
                            <div class="flex-1">
                              <div class="font-medium"><%= user.nickname %></div>
                              <div class="text-sm text-gray-500">@<%= user.account %></div>
                            </div>
                            <button
                              class="ml-3 px-3 py-1 bg-green-600 hover:bg-green-700 text-white text-sm rounded-md transition-colors"
                              phx-click="select_user"
                              phx-value-user-id={user.user_id}
                              phx-target={@myself}
                            >
                              添加好友
                            </button>
                          </div>
                        <% end %>
                      </div>
                    <% end %>

                  </div>

              </div>

            </div>
          </div>
        </div>
      <% end %>


      <div class="flex items-center gap-4">
        <button
          phx-target={@myself}
          phx-click="new_chat"
          class="inline-flex items-center gap-2 bg-green-600 hover:bg-green-700 focus:ring-4 focus:ring-green-200 text-white px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 shadow-sm hover:shadow"
        >
          好友请求
          <span class="bg-gray-100 text-gray-600 text-xs font-medium px-2.5 py-1 rounded-full">
          <%= if @data, do: length(@data), else: 0 %>
        </span>
        </button>
      </div>

    </div>


    <!-- 通知弹窗 -->
    <%= if @show_notification do %>
      <div
        class="fixed inset-0 z-50 flex items-center justify-center pointer-events-none"
        phx-click="hide_notification"
        phx-target={@myself}
      >
        <div class={"px-6 py-4 rounded-lg shadow-lg text-white font-medium pointer-events-auto transform transition-all duration-300 cursor-pointer #{if @notification_type == :success, do: "bg-green-500", else: "bg-red-500"}"}>
          <%= @notification_message %>
          <button
            class="ml-2 text-white hover:text-gray-200"
            phx-click="hide_notification"
            phx-target={@myself}
          >
            ×
          </button>
        </div>
      </div>
    <% end %>

    """
  end

  # 设置页面标题
  defp render_settings_header(assigns) do
    ~H"""
    <div class="flex items-center justify-between">
      <h1 class="text-2xl font-bold text-gray-900">设置</h1>
      <div class="flex items-center gap-3">
        <button
          phx-target={@myself}
          phx-click="save_settings"
          class="inline-flex items-center gap-2 bg-blue-600 hover:bg-blue-700 text-white px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200"
        >
          保存设置
        </button>
      </div>
    </div>
    """
  end

  # 默认标题
  defp render_default_header(assigns) do
    ~H"""
    <div class="flex items-center justify-between">
      <h1 class="text-2xl font-bold text-gray-900">
        <%= @title || "仪表板" %>
      </h1>
    </div>
    """
  end

  # 事件处理函数
  def handle_event("search", %{"value" => search_term}, socket) do
    send(self(), {:search, search_term})
    {:noreply, socket}
  end

  # 打开添加好友模态框
  def handle_event("add_friend", _params, socket) do
    {:noreply, assign(socket, show_add_friend_modal: true)}
  end

  # 关闭添加好友模态框
  def handle_event("close_modal", _params, socket) do
    {:noreply, assign(socket, show_add_friend_modal: false)}
  end

  def handle_event("new_chat", _params, socket) do
    send(self(), :new_chat)
    {:noreply, socket}
  end

  def handle_event("save_settings", _params, socket) do
    send(self(), :save_settings)
    {:noreply, socket}
  end


  # 处理搜索事件
  def handle_event("search_users", %{"value" => search_term_addf}, socket) do
    search_term_addf = String.trim(search_term_addf)

    if String.length(search_term_addf) >= 2 do
      # 调用 Accounts.search_users 函数
      results = Accounts.search_users(search_term_addf)
      {:noreply, assign(socket, search_term_addf: search_term_addf, search_results: results)}
    else
      {:noreply, assign(socket, search_term_addf: search_term_addf, search_results: [])}
    end
  end

    # 处理用户选择
  def handle_event("select_user", %{"user-id" => friend_id}, socket) do
    IO.puts("=== 处理select_user事件 ===")
    current_user_id = socket.assigns.user_id
    IO.inspect({current_user_id, friend_id}, label: "用户ID")

    # 检查是否添加自己为好友
    if current_user_id == friend_id do
      {:noreply, show_notification(socket, :error, "不能添加自己为好友")}
    else
      case UserRelationship.create_user_relationship(%{
        user_a_id: current_user_id,
        user_b_id: friend_id,
        relationship_status: "pending"
      }) do
        {:ok, relationship} ->
          IO.puts("=== 成功创建关系 ===")
          IO.inspect(relationship)

          # 获取被添加用户的信息用于显示
          selected_user = Enum.find(socket.assigns.search_results, &(&1.user_id == friend_id))
          user_name = if selected_user, do: selected_user.nickname || selected_user.account, else: "该用户"

          {:noreply,
            socket
            |> assign(show_add_friend_modal: false, search_results: [], search_term_addf: "", selected_user: nil)
            |> show_notification(:success, "好友请求已发送给 #{user_name}")}

        {:error, changeset} ->
          IO.puts("=== 创建关系失败 ===")
          IO.inspect(changeset.errors, label: "错误信息")

          # 检查具体的错误类型并显示相应信息
          error_message = case changeset.errors do
            errors when is_list(errors) ->
              cond do
                Keyword.has_key?(errors, :user_b_id) and
                String.contains?(inspect(Keyword.get(errors, :user_b_id)), "不能添加自己为好友") ->
                  "不能添加自己为好友"

                Keyword.has_key?(errors, :user_a_id) or Keyword.has_key?(errors, :user_b_id) ->
                  "该好友关系已存在"

                true ->
                  "发送好友请求失败，请重试"
              end
            _ ->
              "发送好友请求失败，请重试"
          end

          {:noreply, show_notification(socket, :error, error_message)}
      end
    end
  end

  # 显示通知的辅助函数
  defp show_notification(socket, type, message) do
    assign(socket,
      show_notification: true,
      notification_type: type,
      notification_message: message
    )
  end

# 隐藏通知
def handle_event("hide_notification", _params, socket) do
  {:noreply, assign(socket, show_notification: false)}
end




end
